package weaver.splittable.db;

import org.apache.log4j.Logger;
import weaver.conn.WeaverConnection;
import weaver.conn.WeaverStatement;
import weaver.splittable.STConfig;
import weaver.splittable.modal.InsertSqlInfo;
import weaver.splittable.modal.UpdateSqlInfo;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class STDBData2SqlUtil {

    private static final Logger LOGGER = Logger.getLogger(STConfig.LOGGER_NAME);

    private static String insert = "INSERT INTO";

    private static String values = "VALUES";

    public static List<InsertSqlInfo> getInsertForCompare(WeaverConnection conn, String sql, String appointTableName){
        List<InsertSqlInfo> insertList = new ArrayList<>();
        ResultSet rs = null;
        WeaverStatement st = null;
        try {
            st = (WeaverStatement) conn.createStatement();
            rs = st.originExecuteQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                StringBuffer columnNameBuffer = new StringBuffer();
                InsertSqlInfo insertSqlInfo = new InsertSqlInfo();
                List<Object> listObject = new ArrayList<>();
                List<String> columnNameList = new ArrayList<>();
                //循环处理字段
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object object = rs.getObject(columnName);
                    listObject.add(object);
                    columnNameBuffer.append(columnName + ",");
                    columnNameList.add(columnName);
                }
                String str = columnNameBuffer.substring(0,columnNameBuffer.length()-1);
                String insertSql = "";
                insertSql = insertSQL(""+appointTableName+"", str);
                insertSqlInfo.setSql(insertSql);
                insertSqlInfo.setObjectList(listObject);
                insertList.add(insertSqlInfo);
            }
        } catch (Exception e) {
            LOGGER.error("Unexpected error occur at getColumnNameAndColumeValue of Data2SqlMysqlUtil, cause: ", e);
        } finally {
            if (rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (st != null){
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return insertList;
    }


    private static String insertSQL(String tableName, String ColumnName) {
        StringBuffer insertSQL = new StringBuffer();
        insertSQL.append(insert).append(" ").append(tableName).append("(").append(ColumnName).append(") ").append(values).append("(").append(")");
        String insertSql = splitInsertSql(insertSQL.toString(), ColumnName.split(",").length);
        return insertSql;
    }


    public static String splitInsertSql(String sqlStr,int length){
        int index=sqlStr.indexOf("(");
        index=sqlStr.indexOf("(", index+1);
        String result=sqlStr.substring(0,index);
        result = result+"(";
        for(int i=1;i<=length;i++){
            if(i==length){
                result+="?";
                break;
            }
            result+="?,";
        }
        result += ")";
        return result;
    }

    public static List<UpdateSqlInfo> getUpdateForCompare(WeaverConnection conn, String sql, String tableName, String keyStr) {
        List<UpdateSqlInfo> updateList = new ArrayList<>();
        ResultSet rs = null;
        WeaverStatement st = null;
        try {
            st = (WeaverStatement) conn.createStatement();
            rs = st.originExecuteQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                StringBuffer columnNameBuffer = new StringBuffer();
                UpdateSqlInfo updateSqlInfo = new UpdateSqlInfo();
                List<Object> listObject = new ArrayList<>();
                List<String> columnNameList = new ArrayList<>();
                int index = 1;
                Long keyValue = 0L;
                //循环处理字段
                for (int i = 1; i <= columnCount; i++) {
                    Object object = rs.getObject(rsmd.getColumnName(i));
                    String columnName = rsmd.getColumnName(i);
                    if (keyStr.equalsIgnoreCase(columnName)){
                        keyValue = Long.valueOf(object.toString());
                    }
                    listObject.add(object);
                    columnNameBuffer.append(columnName + " = ?,");
                    columnNameList.add(columnName);
                }
                String str = columnNameBuffer.substring(0,columnNameBuffer.length()-1);
                updateSqlInfo.setSql(updatetSQL(tableName, str, keyStr));
                updateSqlInfo.setObjectList(listObject);
                updateSqlInfo.setPkValue(keyValue);
                updateList.add(updateSqlInfo);
            }
        } catch (Exception e) {
            LOGGER.error("Unexpected error occur at getColumnNameAndColumeValue of Data2SqlMysqlUtil, cause: ", e);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException e) {
                }
            }
        }
        return updateList;
    }

    /**
     * 拼装updatesql放到list里面
     *
     * @paramColumnName
     * @paramColumnValue
     */
    private static String updatetSQL(String tableName, String columnName,String tablePKcolumeName) {
        String updateSql = "update " + tableName + " set " + columnName + " where " + tablePKcolumeName + " =?";
        return updateSql;
    }

}
